package com.djx.CRUD;

import com.djx.utils.MongoDBUtil;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Insert {

    MongoDBUtil util = MongoDBUtil.getInstance();
    MongoDatabase database = util.getDatabase("d01");
    MongoCollection<Document> collection = database.getCollection("c1");


    /**
     * 添加单条数据
     */
    @Test
    public void TestOneInsert() {
        List<Document> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        List<String> strings = new ArrayList<>();
        strings.add("我是集合one");
        strings.add("我是集合two");
        strings.add("我是集合three");
        strings.add("我是集合four");
        map.put("strings", strings);

        map.put("name", "田佳璇");
        map.put("age", 20);
        map.put("sex", "女");
        map.put("city", "石家庄");


        Document document = new Document(map);
        list.add(document);
        collection.insertMany(list);
        System.out.println("数据库添加成功");
        util.closeDB();
    }

    @Test
    public void TestOneInsert测试() {
        List<Document> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "姚乐乐1");
        map.put("age", 21);
        map.put("sex", "女1");
        map.put("city", "石家庄1");


        Document document = new Document(map);
        list.add(document);
        collection.insertMany(list);
        System.out.println("数据库添加成功");
        util.closeDB();
    }

    /**
     * 添加多条数据
     */
    @Test
    public void TestManyInsert() {
        List<Document> list = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "姚乐乐" + i);
            map.put("age", 20 + i);
            map.put("sex", "女" + i);
            map.put("city", "石家庄" + i);
            Document document = new Document(map);
            list.add(document);
        }
        collection.insertMany(list);
        System.out.println("数据库添加成功");
        util.closeDB();


        for (Document document : list) {
            System.out.println("list数据为:::"+document);
        }
    }
}
